package pl.puntin.punclient.messages;

import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.MultiPixelPackedSampleModel;
import java.awt.image.Raster;
import java.awt.image.SampleModel;
import java.awt.image.WritableRaster;

import javax.naming.directory.InvalidAttributesException;


public final class ImageMessage extends Message
{

	private static final int IMAGE_HEIGHT = 480;
	private static final int IMAGE_WIDTH = 640;
	private final BufferedImage bufferedImage;


	/**
	 * @param bufferedImage musi byc typu BYTE_BINNARY
	 * @throws InvalidAttributesException 
	 */
	public ImageMessage(final BufferedImage bufferedImage)
	{
		if(bufferedImage.getType() != BufferedImage.TYPE_BYTE_BINARY)
			throw new IllegalArgumentException("bufferedImage.TYPE != TYPE_BYTE_BINNARY");
		else if (bufferedImage.getHeight() != IMAGE_HEIGHT)
			throw new IllegalArgumentException("Image has wrong height !");
		else if (bufferedImage.getWidth() != IMAGE_WIDTH)
			throw new IllegalArgumentException("Image has wrong height !");
		
		this.bufferedImage = bufferedImage;
	}
	
	public ImageMessage()
	{
		bufferedImage = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT, BufferedImage.TYPE_BYTE_BINARY);
	}

	@Override
	public byte getType()
	{
		return MessageTypes.IMAGE_MESSAGE;
	}

	@Override
	public byte[] getByteForm()
	{
		DataBufferByte dataBuffer = (DataBufferByte) bufferedImage.getData().getDataBuffer();
		byte[] data = new byte[1+dataBuffer.getSize()];
		
		data[0] = getType();
		for (int i = 1; i < data.length; i++)
		{
			data[i] = dataBuffer.getData(0)[i-1];
		}
		return data;
	}

	public BufferedImage getBufferedImage()
	{
		return bufferedImage;
	}
	
	@Override
	protected void yourDataIsReadyInitYourSelf(final byte[] data)
	{
		DataBufferByte dataBufferByte = new DataBufferByte(data, data.length-1, 1);
		SampleModel sampleModel = new MultiPixelPackedSampleModel(dataBufferByte.getDataType(),
				IMAGE_WIDTH, IMAGE_HEIGHT, 1);
		
		WritableRaster raster = Raster.createWritableRaster(sampleModel, dataBufferByte, null);
		bufferedImage.setData(raster);
		
	}
	

	@Override
	public int getLenght()
	{
		return bufferedImage.getData().getDataBuffer().getSize()+1;
	}
}

